package com.atguigu.pojo.listener;

import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.metadata.CellData;
import com.alibaba.excel.read.listener.ReadListener;
import com.atguigu.pojo.DemoDao;
import com.atguigu.pojo.dto.DemoData;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.ListUtils;


import java.util.ArrayList;
import java.util.List;
import java.util.Map;
@Slf4j
public class DemoDataListener implements ReadListener<DemoData> {
    private static final int BATCH_COUNT =10;//每隔10条存一次数据库
    /*定义集合存储缓存的数据*/
    private List<DemoData> cachedDataList = new ArrayList<>();

    private DemoDao demoDao;
    public DemoDataListener(){
        demoDao = new DemoDao();
    }
    public DemoDataListener(DemoDao demoDao){
        this.demoDao = demoDao;
    }
    @Override
    public void onException(Exception e, AnalysisContext analysisContext) throws Exception {

    }

    @Override
    public void invokeHead(Map<Integer, CellData> map, AnalysisContext analysisContext) {

    }

    /*
    * 每条数据解析时都会调用invoke方法*/
    @Override
    public void invoke(DemoData demoData, AnalysisContext context) {
        log.info("解析到一条数据",demoData);
        cachedDataList.add(demoData);
        if (cachedDataList.size() >=BATCH_COUNT){
            saveData();
            cachedDataList.clear();
        }

    }

    @Override
    public void doAfterAllAnalysed(AnalysisContext analysisContext) {
        saveData();
        log.info("所有数据解析完成");
    }
    private void saveData(){
        log.info("数据开始存储");
        demoDao.save(cachedDataList);
        log.info("数据存储成功");
    }
    @Override
    public boolean hasNext(AnalysisContext analysisContext) {
        return false;
    }
}
